<?php
/**
 * 固码支付
 */

namespace app\api\service\payment;

use app\api\service\ApiPayment;
use app\common\library\exception\OrderException;
use app\common\library\enum\OrderStatusEnum;


class GumaPay extends ApiPayment
{
    public function pay($order)
    {
        return [
            'order_id' => $order['out_trade_no'],
            'pay_seq' => $order['trade_no'],
            'pay_url' => "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}/payment/{$order['trade_no']}",
            'pay_amount' => $order['pay_amount'],
            'amount' => $order['amount']
        ];
    }

    public function notify()
    {
        return $this->verifyOrderNotify();
    }

    /**
     * 回调验签.
     *
     *
     * @return array
     *
     * @throws OrderException
     */
    private function verifyOrderNotify()
    {
        //默认商户ID
        $content = \think\Request::instance()->param('content');
        $sendTime = \think\Request::instance()->param('sendTime');
        preg_match('/[0-9.]+/', $content, $matches); 
        if (empty($matches[0])){
            return;
        }

        $amount = $matches[0];
        //@todo: 根据金额查找十分钟内订单
        $createTime = $sendTime / 1000 - 60 * 10;
        $where = "`channel` = 'G0071' && `create_time` > {$createTime} && `pay_amount` = {$amount} && `status` = " . OrderStatusEnum::UNPAID;
        
        $orderInstance = new \app\common\model\Orders();
        $result = $orderInstance->query("SELECT `trade_no` FROM `pay_orders` WHERE {$where} ORDER BY `id` DESC LIMIT 100");
        if (count($result) == 1){
            return array(
                'trade_no' => $result[0]['trade_no'],
            );
        } else {
            //@todo 出错提示
        }

        
    }

    /**
     * 回调成功参数
     */
    public function callbackSuccessResponse()
    {
        return "ok";
    }
}
